﻿using System;
using System.Globalization;
using System.Text.RegularExpressions;

namespace XospitalParser
{
    internal class LineParser
    {
        private const string regexString =
            @"^(?<date>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{1,3})" +
            @"[\d\s]*(?<logLevel>\w+)" +
            @"\s*Controller: (?<controller>\w+)," +
            @"\s*Action: (?<action>\w+)," +
            @"\s*QueryString: (?<queryString>[\w\W]*)," +
            @"\s*address:(?<address>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})," +
            @"\s*Time: (?<duration>\d+) ms," +
            @"?(\s*User:\s*(?<user>[\w\s\d]+)||([0-9a-f]{32}),)" +
            @"[\s\S]*$";

        private readonly Regex _regex = new Regex(regexString);

        public UserAction Parse(string s)
        {
            Match match = _regex.Match(s);
            string controllerName = match.Groups["controller"].Value;
            if(match.Success && !String.IsNullOrEmpty(controllerName))
            {
                string dateTimeString = match.Groups["date"].Value;
                //TODO: null
                DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm:ss,fff", DateTimeFormatInfo.InvariantInfo);
                return new UserAction(
                    dateTime, 
                    controllerName,
                    match.Groups["action"].Value,
                    match.Groups["queryString"].Value,
                    match.Groups["address"].Value,
                    int.Parse(match.Groups["duration"].Value),
                    match.Groups["user"].Value);
            }
            return null;
        }
    }
}